package com.dlb.andorid.fragment;

import android.app.Dialog;
import android.os.Bundle;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.dlb.andorid.App;
import com.dlb.andorid.ProductAdapter;
import com.dlb.andorid.R;
import com.dlb.andorid.XContract;
import com.dlb.andorid.activity.OrderSureActivity;
import com.dlb.andorid.activity.ProductDetailActivity;
import com.dlb.andorid.bean.ArgAddOrder;
import com.dlb.andorid.bean.ArgCar;
import com.dlb.andorid.bean.Car;
import com.dlb.andorid.bean.Order;
import com.dlb.andorid.bean.ProductBean;
import com.dlb.andorid.bean.ServerResult;
import com.dlb.andorid.presenter.CarPresenter;
import com.kwan.xframe.mvp.view.fragment.BasePageItemFragment;
import com.kwan.xframe.util.DialogFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;


public class CarFragment extends BasePageItemFragment implements XContract.ICarView {


	public static CarFragment newInstance() {
		CarFragment fragment = new CarFragment();
		Bundle args = new Bundle();
		fragment.setArguments(args);
		return fragment;
	}


	@Override
	protected String getItemTag() {
		return "Car";
	}


	RecyclerView rv_car_rec, rv_car;

	BaseQuickAdapter<ProductBean, BaseViewHolder> mRecAdapter;
	BaseQuickAdapter<Car, BaseViewHolder> mCarAdapter;

	List<Car> mCars = new ArrayList<>();
	List<ProductBean> mRecommendProducts = new ArrayList<>();
	CheckBox cb_select_all;
	View tv_pay;
	TextView tv_price;
	CarPresenter mPresenter;

	TreeMap<Car, Integer> selectCar = new TreeMap<>();


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mPresenter = new CarPresenter(this);

		cb_select_all = mContentView.findViewById(R.id.cb_select_all);
		tv_pay = mContentView.findViewById(R.id.tv_pay);
		tv_price = mContentView.findViewById(R.id.tv_price);

		cb_select_all.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

				if (b && (mCars == null || mCars.size() == 0)) {
					cb_select_all.setChecked(false);
					cb_select_all.setEnabled(false);
					toastMsg("购物车中没有商品");
					return;
				}

				for (Car car : mCars) {
					car.setSelected(b);
					mCarAdapter.notifyDataSetChanged();
				}
				upDataPrice();

			}
		});

		tv_pay.setOnClickListener(this);


		rv_car_rec = mContentView.findViewById(R.id.rv_car_rec);
		rv_car_rec.setLayoutManager(new GridLayoutManager(mBaseActivity, 2, LinearLayoutManager.VERTICAL, false));
		rv_car_rec.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		rv_car_rec.setLayerType(View.LAYER_TYPE_HARDWARE, null);
		rv_car_rec.setHasFixedSize(true);
		rv_car_rec.setItemAnimator(null);
		rv_car_rec.setNestedScrollingEnabled(false);

		mRecAdapter = new ProductAdapter(mRecommendProducts);
		mRecAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
			@Override
			public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
				//toastMsg(""+mProducts.get(position).getId());
				Log.e("kwan", "car:" + mRecommendProducts.get(position).getId());
				if (view.getId() == R.id.iv_car) {
					Log.e("kwan", "car:" + mRecommendProducts.get(position).getId());
					mBaseActivity.showProgress("");
					mPresenter.addCar(mRecommendProducts.get(position).getId(), App.mUserInfo.getUid(), 1, mRecommendProducts.get(position).getType_id(), mRecommendProducts.get(position).getSale_price());
				}
			}
		});

		mRecAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
			@Override
			public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
				Bundle bundle = new Bundle();
				bundle.putLong("id", mRecommendProducts.get(position).getId());
				go2Activity(ProductDetailActivity.class, bundle, false);
			}
		});

		rv_car_rec.setAdapter(mRecAdapter);

		rv_car = mContentView.findViewById(R.id.rv_car);
		rv_car.setLayoutManager(new LinearLayoutManager(mBaseActivity));
		rv_car.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		rv_car.setLayerType(View.LAYER_TYPE_HARDWARE, null);
		rv_car.setHasFixedSize(true);
		rv_car.setItemAnimator(null);
		rv_car.setNestedScrollingEnabled(false);

		mCarAdapter = new BaseQuickAdapter<Car, BaseViewHolder>(R.layout.list_item_car, mCars) {
			@Override
			protected void convert(final BaseViewHolder helper, Car item) {

				mImageLoader.loadUrl(item.getPic_cover(), (ImageView) helper.getView(R.id.iv_icon));

				helper.setText(R.id.tv_name, item.getCommodity_name() + " " + item.getType_name());
				helper.setText(R.id.tv_price, "¥ " + item.getSale_price());
				helper.setText(R.id.tv_price_wholesale, "¥ " + item.getWholesale_price());
				helper.setVisible(R.id.tv_price_wholesale, App.mUserInfo.getUser_group() == 6);
				helper.setText(R.id.tv_num, "" + item.getNum());
				helper.addOnClickListener(R.id.tv_add);
				helper.addOnClickListener(R.id.tv_minus);
				helper.setChecked(R.id.rb_check, item.isSelected());
				helper.setOnCheckedChangeListener(R.id.rb_check, new CompoundButton.OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
						mCars.get(helper.getLayoutPosition()).setSelected(b);
						upDataPrice();
					}
				});

			}
		};

		mCarAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
			@Override
			public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

				Car car = mCars.get(position);
				if (view.getId() == R.id.tv_add) {

					car.setNum(car.getNum() + 1);
					mCarAdapter.notifyItemChanged(position);
					mPresenter.editCarNum(car.getShopping_cart_id(), car.getNum());

				} else if (view.getId() == R.id.tv_minus) {
					if (car.getNum() > 1) {
						car.setNum(car.getNum() - 1);
						mCarAdapter.notifyItemChanged(position);
						mPresenter.editCarNum(car.getShopping_cart_id(), car.getNum());
					} else {
						showDeleteCarDialog(car, position);
					}
				}

				upDataPrice();
			}
		});

		rv_car.setAdapter(mCarAdapter);
	}

	float mPrice = 0.00f;

	private void upDataPrice() {

		mPrice = 0.00f;
		for (Car car : mCars) {
			if (car.isSelected()) {

				float price = App.mUserInfo.getUser_group() == 6 ? car.getWholesale_price() : car.getSale_price();

				mPrice = mPrice + price * car.getNum();
			}
		}

		tv_price.setText("合计:¥" + mPrice);
	}

	public void showDeleteCarDialog(final Car car, final int position) {

		View view = getLayoutInflater().inflate(R.layout.layout_common_dialog, null);
		((TextView) view.findViewById(R.id.tv_msg)).setText("是否删除购物车");
		final Dialog dialog = DialogFactory.showCustomDialog(mBaseActivity, view);
		view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		view.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mCars.remove(position);
				mCarAdapter.notifyDataSetChanged();
				mPresenter.editCarNum(car.getShopping_cart_id(), 0);
				dialog.dismiss();
				upDataPrice();
			}
		});

		dialog.show();
	}


	@Override
	public void onResume() {
		super.onResume();
		mPresenter.getCars();
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		if (v == tv_pay) {

			List<ArgCar> data = new ArrayList<>();
			for (Car car : mCars) {
				if (car.isSelected()) {
					ArgCar argCar = new ArgCar();
					argCar.setCommodity_id(car.getCommodity_id());
					argCar.setCommodity_num(car.getNum());
					data.add(argCar);
				}
			}

			if (data.size() <= 0) {
				toastMsg("请选择商品");
				return;
			}

			ArgAddOrder arg = new ArgAddOrder();
			arg.setUser_id(App.mUserInfo.getUid());
			arg.setData(data);
			mPresenter.addOrder(arg);

		}

	}


	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onStop() {
		super.onStop();
	}


	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected int getContentViewId() {
		return R.layout.fragment_car;
	}

	//第一次获取数据
	@Override
	public void fetchData() {
		mBaseActivity.showProgress("");
		mPresenter.getRecommendProducts();
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (isVisibleToUser)
			mPresenter.getCars();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	@Override
	public String getPageName() {
		return null;
	}

	@Override
	public void getCarSuccess(List<Car> data) {
		mBaseActivity.dismissProgress();
		mCars.clear();
		mCars.addAll(data);
		mCarAdapter.notifyDataSetChanged();
		cb_select_all.setEnabled(mCars.size() > 0);

	}

	@Override
	public void addCarSuccess(ServerResult data) {
		dismissProgress();
		toastMsg(data.getMsg());
		mPresenter.getCars();
	}

	@Override
	public void getRecommendProductsSuccess(List<ProductBean> data) {
		mRecommendProducts.clear();
		mRecommendProducts.addAll(data);
		mRecAdapter.notifyDataSetChanged();
	}

	@Override
	public void editCarNumSuccess(String str) {
		Log.e("kwan", "editCarNumSuccess:" + str);

	}

	@Override
	public void addOrderSuccess(Order data) {
		Log.e("kwan", data.getOrder_no());
		Bundle bundle = new Bundle();
		bundle.putSerializable("order", data);
		go2Activity(OrderSureActivity.class, bundle, false);
	}
}
